package com.ljkj.cordial.chat.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.DaoSession;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.fresco.ImageLoader;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.util.glide.GlideUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GroupMemberAvatarAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<FriendTable> list = new ArrayList<>();
    private String groupId;

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    private boolean isGroupOwner;

    public void setList(List<FriendTable> list, boolean groupOwner) {
        isGroupOwner = groupOwner;
        if (list == null || list.isEmpty()) {
            return;
        }
        this.list = list;
        addFoot();
        notifyDataSetChanged();
    }

    public void addList(List<FriendTable> list, boolean groupOwner) {
        isGroupOwner = groupOwner;
        if (list == null || list.isEmpty()) {
            return;
        }
        removeFoot();
        int s = this.list.size();
        this.list.addAll(list);
        addFoot();
        notifyItemRangeChanged(s, getItemCount());
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View convertView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_group_member, null);
        return new AvatarViewHolder(convertView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
        AvatarViewHolder avatarViewHolder = (AvatarViewHolder) holder;
        FriendTable item = list.get(i);
        if ("1".equals(item.getFriendId())) {//+
            avatarViewHolder.tvName.setVisibility(View.INVISIBLE);
            avatarViewHolder.itemImg.setImageResource(R.mipmap.group_btn_add_member_n);
            avatarViewHolder.itemImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onMemberClickListener != null) {
                        onMemberClickListener.onClick(list.size(), v, Canstants.MEMBER_STATE_ADD, null);
                    }
                }
            });
        } else if ("2".equals(item.getFriendId())) {//-
            avatarViewHolder.tvName.setVisibility(View.INVISIBLE);
            avatarViewHolder.itemImg.setImageResource(R.mipmap.group_btn_reduce_member_n);
            avatarViewHolder.itemImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onMemberClickListener != null) {
                        onMemberClickListener.onClick(list.size() + 1, v, Canstants.MEMBER_STATE_REMOVE, null);
                    }
                }
            });
        } else {
            avatarViewHolder.tvName.setVisibility(View.VISIBLE);
            avatarViewHolder.tvName.setText(TextUtils.isEmpty(item.getFriendAlias()) ? item.getFriendNickname() : item.getFriendAlias());
//            if (item.getFriendUserId().equals(ChatApp.getInstance().getUserId())) {
//                ImageLoader.getInstance().displayUserAvatar(item.getFriendAvatar(), avatarViewHolder.itemImg);
//            } else
//                ImageLoader.getInstance().displayGroupMemberAvatar(groupId, item.getFriendUserId(), item.getFriendAvatar(), avatarViewHolder.itemImg);

            if (!TextUtils.isEmpty(item.getFriendAvatarPath())) {
                String tag = (String) avatarViewHolder.itemImg.getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(item.getFriendAvatar())) {
                    avatarViewHolder.itemImg.setTag(com.nic.view.R.id.glide_image_id, item.getFriendAvatar());
                }
                GlideUtil.getInstance().load(item.getFriendAvatarPath(), avatarViewHolder.itemImg);
            } else {
                if (TextUtils.isEmpty(item.getFriendAvatar())) {
                    GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, avatarViewHolder.itemImg);
                } else {
                    String tag = (String) avatarViewHolder.itemImg.getTag(com.nic.view.R.id.glide_image_id);
                    if (TextUtils.isEmpty(tag) || tag.equals(item.getFriendAvatar())) {
                        avatarViewHolder.itemImg.setTag(com.nic.view.R.id.glide_image_id, item.getFriendAvatar());
                    }
                    AlbumManageUtil.getInstance().downLoadFileFriendAvatar(item.getFriendAvatar(), item.getFriendUserId(), new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onResult(String url, String locPath) {
                            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(locPath)) {
                                GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, avatarViewHolder.itemImg);
                                return;
                            }
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<String>() {
                                @Override
                                public void onAction(String obj) {
                                    GlideUtil.getInstance().load(obj, avatarViewHolder.itemImg);
                                }

                                @Override
                                public String onThreadAction() {
                                    GroupMemberTable g = GroupMemberTable.query(groupId, item.getFriendUserId());
//                                    String path = TextUtils.isEmpty(al.getMThumbPath()) ? al.getMPath() : al.getMThumbPath();
//                                     && (TextUtils.isEmpty(g.getGroupMemberAvatarPath()) ||
//                                            (!TextUtils.isEmpty(g.getGroupMemberAvatarPath()) && !g.getGroupMemberAvatarPath().equals(path)))
                                    if (g != null) {
                                        g.setGroupMemberAvatar(item.getFriendAvatar());
//                                        g.setGroupMemberAvatarId(fileId);
                                        g.setGroupMemberAvatarPath(locPath);
                                        GroupMemberTable.update(g);
                                    }
                                    return locPath;
                                }
                            });
                        }
                    });
                    GlideUtil.getInstance().load(item.getFriendAvatarPath(), avatarViewHolder.itemImg);
                }
            }
            avatarViewHolder.itemImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onMemberClickListener != null) {
                        onMemberClickListener.onClick(i, v, Canstants.MEMBER_STATE_NORMAL, item);
                    }
                }
            });
        }
    }

//    private void updateGroupMemberAvatar(String fileId, AlbumTableBean fil, FriendTable item) {
//        GroupMemberTable m = GroupMemberTable.query(groupId, item.getFriendUserId());
//        if (m != null) {
//            m.setGroupMemberAvatarId(fileId);
//            m.setGroupMemberAvatarPath(TextUtils.isEmpty(fil.getMThumbPath()) ? fil.getMPath() : fil.getMThumbPath());
//            GroupMemberTable.insertOrUpdate(m);
//        }
//        ChatContentTable chatContentTable = ChatContentTable.queryRowByTargetId(groupId, Canstants.GROUP_CHAT);
//        if (chatContentTable != null) {
//            String[] v = GroupMemberTable.getAvatarEntityLoc(groupId);
//            if (v != null) {
//                chatContentTable.setTargetMemberUserId(v[0]);
//                chatContentTable.setTargetAvatarUrl(v[1]);
//                chatContentTable.setTargetAvatarPath(v[2]);
//                ChatContentTable.insertNotUpdateNumber(chatContentTable);
//            }
//        }
////        List<ChatTableBean> chatList = ChatTableBean.query(Canstants.GROUP_CHAT, item.getFriendUserId(), item.getFriendUserId(), 0, 999);
//    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public List<FriendTable> getList() {
        return list;
    }

    public void addFoot() {
        Iterator<FriendTable> it = list.iterator();
        while (it.hasNext()) {
            FriendTable table = it.next();
            if ("1".equals(table.getFriendId()) || "2".equals(table.getFriendId())) {
                it.remove();
            }
        }
        FriendTable f = new FriendTable();
        f.setFriendId("1");
        list.add(f);
        if (isGroupOwner) {
            FriendTable f2 = new FriendTable();
            f2.setFriendId("2");
            list.add(f2);
        }
    }

    public void removeByMemberUserId(String memberId) {
        boolean isNotify = false;
        for (int i = 0; i < list.size(); i++) {
            FriendTable table = list.get(i);
            if (!"1".equals(table.getFriendId()) && !"2".equals(table.getFriendId())) {
                if (table != null && memberId.contains(table.getFriendUserId())) {
                    list.remove(i--);
                    isNotify = true;
                }
            }
        }
        if (isNotify)
            notifyDataSetChanged();
    }

    public void removeFoot() {
        Iterator<FriendTable> it = list.iterator();
        while (it.hasNext()) {
            FriendTable table = it.next();
            if ("1".equals(table.getFriendId()) || "2".equals(table.getFriendId())) {
                it.remove();
            }
        }
    }

    static
    class AvatarViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.item_img)
        ImageView itemImg;
        @BindView(R.id.tv_name)
        TextView tvName;

        AvatarViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            setIsRecyclable(false);
        }
    }

    private OnMemberClickListener onMemberClickListener;

    public void setOnMemberClickListener(OnMemberClickListener onMemberClickListener) {
        this.onMemberClickListener = onMemberClickListener;
    }

    public interface OnMemberClickListener {
        void onClick(int position, View v, int footState, FriendTable item);
    }

    public void modifyGroupMamberAlias(int position, String alias) {
        if (position <= list.size()) {
            list.get(position).setFriendAlias(alias);
            notifyItemChanged(position);

        }
    }

    public List<FriendTable> getData() {
        List<FriendTable> userInfors = new ArrayList<>();
        for (FriendTable bean : getList()) {
            if (!"1".equals(bean.getFriendId()) &&
                    !"2".equals(bean.getFriendId())) {
                userInfors.add(bean);
            }
        }
        return userInfors;
    }

    public List<FriendTable> getDataNotMe(String meId) {
        List<FriendTable> userInfors = new ArrayList<>();
        for (FriendTable bean : getList()) {
            if (!"1".equals(bean.getFriendId()) &&
                    !"2".equals(bean.getFriendId()) &&
                    !meId.equals(bean.getFriendUserId())) {
                userInfors.add(bean);
            }
        }
        return userInfors;
    }
}
